using System;
using UnityEngine;

namespace DanielSig.Geometry
{
	[Serializable]
	public class SharpEdge
	{
		
		/// <summary>
		///A sharp edge of a mesh, used for determine if 
		///another mesh should split apart/take damage from impact with this mesh. 
		/// </summary>
		/// <param name="start">
		/// The first vertex.
		/// </param>
		/// <param name="end">
		/// The second vertex.
		/// </param>
		/// <param name="normal">
		/// The edge's direction.
		/// </param>
		/// <param name="thickness">
		/// The thickness of the edge.
		/// </param>
		/// <param name="sharpness">
		/// The sharpness of the edge.
		/// </param>
		public SharpEdge(Line3D line, Vector3 normal, float sharpness)
		{
			Line = line;
			Normal = normal;
			Sharpness = sharpness;
		}
		public SharpEdge(Vector3 start, Vector3 end, Vector3 normal, float thickness, float sharpness)
		{
			Line = new Line3D(ref start, ref end, thickness);
			Normal = normal;
			Sharpness = sharpness;
		}
		public SharpEdge(ref Vector3 start, ref Vector3 end, ref Vector3 normal, float thickness, float sharpness)
		{
			Line = new Line3D(ref start, ref end, thickness);
			Normal = normal;
			Sharpness = sharpness;
		}
		public bool InflictsDamage(Vector3 contactPoint, Vector3 contactNormal, Vector3 velocity)
		{
			if(Line.IsPointOnLine(contactPoint))
			{
				float damage = 1F;//(1F - Vector3.Dot(Normal, contactNormal).Abs());
				//damage		*= damage * damage;
				damage 		*= (1F - Vector3.Dot(Normal, velocity.normalized).Abs());
				damage		*= velocity.magnitude;
				if(damage > 1F / (0.0001F + Sharpness) + 3)
				{
					return true;
				}
			}
			return false;
		}
		public static SharpEdge operator +(SharpEdge a, SharpEdge b)
		{
			Vector3 normal = (a.Normal + b.Normal).normalized;
			float sharpness = (a.Sharpness + b.Sharpness) * 0.5F;
			Line3D line = a.Line + b.Line;
			return new SharpEdge(line, normal, sharpness);
		}
		public readonly Line3D Line;
		public readonly Vector3 Normal;
		public readonly float Sharpness;
	}
}

